package org.wenhua.yuan.views.edt;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.wenhua.yuan.R;
import org.wenhua.yuan.views.DisplayUtils;

import java.util.List;

/**
 * @author yuanjunh
 * @date 2023/02/13
 * @describe 搜索编辑框
 */
public class EdtSearchView extends LinearLayout implements TextWatcher, TextView.OnEditorActionListener {

    private EditText edit; //输入框
    private ImageView imgClean; //删除图标
    private String searchText;      //改变后的文字
    private boolean isButton;      //是否点击进入下一页进行搜索

    public EdtSearchView(Context context) {
        this(context, null, 0);
    }

    public EdtSearchView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public EdtSearchView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initTypedArray(context, attrs, defStyleAttr);
    }

    private void initTypedArray(Context context, AttributeSet attrs, int defStyleAttr) {
        setOrientation(LinearLayout.HORIZONTAL);
        setGravity(Gravity.CENTER_VERTICAL);
        //读取属性
        TypedArray typed = context.obtainStyledAttributes(attrs, R.styleable.EdtSearchView);

        // 左侧搜索图标
        ImageView imgSearch = new ImageView(context);
        LinearLayout.LayoutParams searchParam = new LinearLayout.LayoutParams(DisplayUtils.dp2px(20), DisplayUtils.dp2px(20));
        searchParam.leftMargin = DisplayUtils.dp2px(4);
        searchParam.rightMargin = DisplayUtils.dp2px(2);
        imgSearch.setLayoutParams(searchParam);
        imgSearch.setImageTintList(ColorStateList.valueOf(getResources().getColor(R.color.colorCMBCWhiteLight)));
        imgSearch.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.titlebar_search));
        addView(imgSearch);

        // 中间edit
        edit = new EditText(context);
        LinearLayout.LayoutParams editParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        editParam.weight = 1;
        editParam.gravity = Gravity.CENTER_VERTICAL;
        edit.setLayoutParams(editParam);
        edit.setPadding(0, DisplayUtils.dp2px(6),0,DisplayUtils.dp2px(6));
        edit.setSingleLine(true);
        final float editTextSize = typed.getDimension(R.styleable.EdtSearchView_jh_textSize, 16);
        edit.setTextSize(TypedValue.COMPLEX_UNIT_PX, editTextSize);
//        Log.d("EdtSearchView", "editTextSize=="+editTextSize);
        final int editTextColor = typed.getColor(R.styleable.EdtSearchView_jh_textColor, getResources().getColor(R.color.colorAccent));
        edit.setTextColor(editTextColor);
        edit.setHintTextColor(getResources().getColor(R.color.colorCMBCWhiteLight));
        final String hint = typed.getString(R.styleable.EdtSearchView_jh_hint);
        edit.setHint(hint);
        searchText = typed.getString(R.styleable.EdtSearchView_jh_text);
        if (TextUtils.isEmpty(searchText)) {
            edit.setText(searchText);
        } else {
            edit.setText("");
        }
        isButton = typed.getBoolean(R.styleable.EdtSearchView_jh_button, false);
        edit.setFocusable(!isButton);

        edit.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        edit.setBackground(null);
        addView(edit);

        // 右侧clean图标
        imgClean = new ImageView(context);
        LinearLayout.LayoutParams cleanParam = new LinearLayout.LayoutParams(DisplayUtils.dp2px(20), DisplayUtils.dp2px(20));
        cleanParam.leftMargin = DisplayUtils.dp2px(2);
        cleanParam.rightMargin = DisplayUtils.dp2px(4);
        imgClean.setLayoutParams(cleanParam);
        imgClean.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.clear_circle));
        imgClean.setImageTintList(ColorStateList.valueOf(getResources().getColor(R.color.colorCMBCWhiteLight)));
        final boolean hidden = typed.getBoolean(R.styleable.EdtSearchView_jh_hideImg, true);
        imgClean.setVisibility(hidden?View.GONE:View.VISIBLE);
        addView(imgClean);

        setBackground(getResources().getDrawable(R.drawable.edtsearch_view_drawable));

        typed.recycle();

        //设置清空按钮的触发器
        imgClean.setOnClickListener(v -> edit.setText(""));
        //回收资源
        //文字改变监听
        edit.addTextChangedListener(this);
        edit.setOnEditorActionListener(this);
        Log.d("EdtSearchView", "isButton=="+isButton);
        if (isButton) {
            edit.setOnClickListener(v->Toast.makeText(getContext(), "Edit点击跳转", Toast.LENGTH_SHORT).show());
        }
    }


    /**
     * 获取搜索框的文字
     */
    public String getText(){
        return edit.getText().toString();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        //删除图标处理
        if (s.toString().isEmpty()){
            imgClean.setVisibility(GONE);
        }else {
            imgClean.setVisibility(VISIBLE);
        }

        searchText = s.toString();
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            Log.i("EdtSearchView","搜索操作执行");
            Toast.makeText(getContext(), "搜索中...", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    /**
     * 用于匹配项,匹配预制的、搜索记录等搜索内容
     */
    public static abstract class SearchWay<T>{
        /**
         * @return 数据源
         */
        public abstract List<T> getData();

        /**
         * @return item中是否包含有s
         */
        public abstract boolean matchItem(T item, String s);

        /**
         * 更新列表
         * @param resultList 匹配的数据，重新加载到列表
         */
        public abstract void update(List<T> resultList);
    }
}